import { Menu, Icon } from 'ant-design-vue'
import routes from '@/router/routes'
const { SubMenu, Item } = Menu
export default {
  name: 'Menu',
  data() {
    return {
      path: this.$route.path
    }
  },
  computed: {
    defaultOpenKeys() {
      return this.queryOpenKeys(routes, [], this.path) || []
    }
  },
  methods: {
    // 根据叶子结点，获取父节点路径
    queryOpenKeys(routes, keys, leafKey) {
      let result = null
      for (const route of routes) {
        if (route.children && route.children.length) {
          result = this.queryOpenKeys(route.children, [...keys, route.path], leafKey)
        } else {
          if (route.path === leafKey) {
            result = keys
          }
        }
        if (result) {
          break
        }
      }
      return result
    },
    generateMenus(routes) {
      return routes.map(route => {
        if (route.children && route.children.length) {
          return (
            <SubMenu key={route.path}>
              <span slot="title">
                <Icon type="appstore" />
                <span>{route.name}</span>
              </span>
              {this.generateMenus(route.children)}
            </SubMenu>
          )
        } else {
          return (
            <Item key={route.path}>
              <router-link to={route.path}>
                <Icon type="appstore" />
                <span>{route.name}</span>
              </router-link>
            </Item>
          )
        }
      })
    }
  },
  render() {
    return (
      <Menu {...{ props: { theme: 'dark', mode: 'inline', defaultOpenKeys: this.defaultOpenKeys, defaultSelectedKeys: [this.path] } }}>
        {this.generateMenus(routes)}
      </Menu>
    )
  }
}
